import React, { useEffect, useState } from 'react';
import { Button, Dropdown } from "@douyinfe/semi-ui";
import { localeOptions } from "@shared/consts";
import { useStore } from "@shared/store";
import { IAdminStore } from "@shared/types";

export type LocaleSelectorProps = { 
    position: 'bottom' | 'top'
};

const findLocaleName = (locale: string): string => {
    for (let option of localeOptions) {
        if (option.value === locale) return option.src && option.src.short ? option.src.short : option.label;
    }
    return locale;
}

const LocaleSelector = (props: LocaleSelectorProps) => {
    const store = useStore<IAdminStore>();
    const [ localeName, setLocaleName ] = useState<string>();

    useEffect(() => {
        setLocaleName(findLocaleName(store.locale));
    }, []);

    return <Dropdown
        trigger={'click'}
        position={props.position}
        render={
            <Dropdown.Menu>
                {
                    localeOptions.map(item => {
                        return <Dropdown.Item onClick={() => {
                            store.switchLocale(item.value as string);
                        }}>{item.label}</Dropdown.Item>;
                    })
                }
            </Dropdown.Menu>
        }
    >
        <Button style={{ color: 'var(--semi-color-text-1)', fontWeight: 'bold' }}>{localeName}</Button>
    </Dropdown>;
}

export default LocaleSelector;